package com.tmt.im.service.helper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.MessageFormat;
import java.util.Objects;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/3 11:54
 * @Version 1.0
 **/
@Slf4j
public class MySqlHelper {

    public static void executeBy(String sql, Object[] sqlParams, DataSourceProperties dataSourceProperties) {
        try (Connection conn = DriverManager.getConnection(dataSourceProperties.getUrl(), dataSourceProperties.getUsername(),
                dataSourceProperties.getPassword())) {
            try (PreparedStatement st = conn.prepareStatement(sql)) {
                //初始化SQL中的参数
                if (sqlParams != null) {
                    initPreparedStatement(st, sqlParams);
                }
                st.execute();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    public static void initPreparedStatement(PreparedStatement st, Object[] sqlParams) throws Exception {
        for (int i = 0; i < sqlParams.length; i++) {
            Class<?> paramType = sqlParams[i].getClass();
            String name = paramType.getSimpleName();
            if (int.class.getSimpleName().equals(name) || Integer.class.getSimpleName().equals(name)) {
                name = "Int";
            } else if (boolean.class.getSimpleName().equals(name) || Boolean.class.getSimpleName().equals(name)) {
                name = "Boolean";
            } else if (long.class.getSimpleName().equals(name) || Long.class.getSimpleName().equals(name)) {
                name = "Long";
            }

            if (Objects.equals(paramType, Long.class)) {
                paramType = long.class;
            } else if (Objects.equals(paramType, Boolean.class)) {
                paramType = boolean.class;
            } else if (Objects.equals(paramType, Integer.class)) {
                paramType = int.class;
            }

            String methodName = MessageFormat.format("set{0}", name);
            Method method = st.getClass().getMethod(methodName, int.class, paramType);
            if (sqlParams[i] == null) {
                method = st.getClass().getMethod("setObject", int.class, Object.class);
                method.invoke(st, i + 1, null);
            } else {
                method.invoke(st, i + 1, sqlParams[i]);
            }
        }
    }
}
